
import datetime

from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager as _UserManager
from django.db.models.signals import post_save
from django.dispatch import receiver

from utils.models import ModelBase
from apps.searches.models import IdcN


class UserManager(_UserManager):
    """

    """
    def create_superuser(self, username, password, email=None, **extra_fields):
        super(UserManager, self).create_superuser(username=username,
                                                  password=password,
                                                  email=email, **extra_fields)

class Users(AbstractUser):
    """
    add mobile 、email_active fields to Django users modules.
    """
    REQUIRED_FIELDS = ['mobile']
    objects = UserManager()

    mobile = models.CharField(max_length=11, unique=True, help_text="手机号", verbose_name="手机号",
                              error_messages={
                                  'unique': "此手机号已经注册", },
                              )
    email_active = models.BooleanField(default=False, verbose_name='邮箱验证状态')
    idcn = models.ForeignKey(IdcN, verbose_name='机房名称', on_delete=models.CASCADE,null=True)  # 外键

    class Meta:
        db_table = 'tb_users'
        verbose_name = "用户"
        verbose_name_plural = verbose_name

    def get_groups_name(self):
        groups_name_list = [i.name for i in self.groups.all()]
        return ' | '.join(groups_name_list)

    def __str__(self):
        return self.username


class UsersProfile(ModelBase):
    """create users profile model
    """
    GENDER_CHOICES = (
        ('M', '男'),
        ('F', '女'),
    )
    user = models.OneToOneField(Users, on_delete=models.CASCADE, related_name='user_profile')
    nickname = models.TextField(max_length=100, null=True, blank=True, verbose_name='昵称', help_text='昵称')
    born_date = models.DateField(null=True, blank=True)
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M')
    motto = models.TextField(max_length=1024, null=True, blank=True)

    class Meta:
        db_table = 'tb_users_profile'
        verbose_name = "用户个人信息"
        verbose_name_plural = verbose_name


@receiver(post_save, sender=Users)
def create_user_profile(sender, **kwargs):
    """create user profile function
    """
    # created
    if kwargs.get('created', False):
        user_profile = UsersProfile.objects.get_or_create(user=kwargs.get('instance'))
        if user_profile[-1]:
            user_profile = user_profile[0]
            user_profile.nickname = '老王'
            user_profile.born_date = datetime.date(1999, 11, 11)
            user_profile.motto = '我是老王，我怕谁！'
            user_profile.save()


class Userip(ModelBase):
    ip = models.CharField(verbose_name='IP地址', max_length=30)  # ip地址
    count = models.IntegerField(verbose_name='访问次数', default=0)  # 该ip访问次数

    class Meta:
        verbose_name = '访问用户信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.ip

    # 网站总访问次数


class VisitNumber(ModelBase):
    count = models.IntegerField(verbose_name='网站访问总次数', default=0)  # 网站访问总次数

    class Meta:
        verbose_name = '网站访问总次数'
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.count)

